﻿using System;
using System.IO;
using SevenZip;
using SevenZip.Compression.LZMA;

namespace FootSteps.Data
{
    public static class SevenZipHelper
    {

        private static int dictionary = 1 << 23;

        // static Int32 posStateBits = 2;
        // static  Int32 litContextBits = 3; // for normal files
        // UInt32 litContextBits = 0; // for 32-bit data
        // static  Int32 litPosBits = 0;
        // UInt32 litPosBits = 2; // for 32-bit data
        // static   Int32 algorithm = 2;
        // static    Int32 numFastBytes = 128;

        private static bool eos = false;





        private static CoderPropID[] _propIDs =
        {
            CoderPropID.DictionarySize,
            CoderPropID.PosStateBits,
            CoderPropID.LitContextBits,
            CoderPropID.LitPosBits,
            CoderPropID.Algorithm,
            CoderPropID.NumFastBytes,
            CoderPropID.MatchFinder,
            CoderPropID.EndMarker
        };

        // these are the default properties, keeping it simple for now:
        private static object[] _properties =
        {
            dictionary,
            2,
            3,
            0,
            2,
            128,
            "bt4",
            eos
        };


        public static byte[] Compress(byte[] inputBytes)
        {

            var inStream = new MemoryStream(inputBytes);
            var outStream = new MemoryStream();
            var encoder = new Encoder();
            encoder.SetCoderProperties(_propIDs, _properties);
            encoder.WriteCoderProperties(outStream);
            var fileSize = inStream.Length;
            for (var i = 0; i < 8; i++)
                outStream.WriteByte((Byte) (fileSize >> (8*i)));
            encoder.Code(inStream, outStream, -1, -1, null);
            return outStream.ToArray();
        }

        public static byte[] Decompress(byte[] inputBytes)
        {
            var newInStream = new MemoryStream(inputBytes);

            var decoder = new Decoder();

            newInStream.Seek(0, 0);
            var newOutStream = new MemoryStream();

            var properties2 = new byte[5];
            if (newInStream.Read(properties2, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            long outSize = 0;
            for (var i = 0; i < 8; i++)
            {
                var v = newInStream.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long) (byte) v) << (8*i);
            }
            decoder.SetDecoderProperties(properties2);

            var compressedSize = newInStream.Length - newInStream.Position;
            decoder.Code(newInStream, newOutStream, compressedSize, outSize, null);

            var b = newOutStream.ToArray();

            return b;



        }


    }
}
